import 'dart:async';

import 'package:app_network/app_network.dart';
import 'package:flutter/material.dart';
import 'package:flutter_baseui_kit/flutter_baseui_kit.dart';
import 'package:flutter_cache_kit/flutter_cache_kit.dart';
import 'package:flutter_effect/flutter_effect.dart';
import 'package:flutter_network_kit/flutter_network_kit.dart';
import 'package:flutter_theme_helper/flutter_theme_helper.dart';
import './tsdemo_publish_page.dart';

class WishPublishHomePage extends BJHBasePage {
  static bool isPresent = false;
  WishPublishHomePage({Key key, bool present}) : super(key: key) {
    WishPublishHomePage.isPresent = present ?? false;
  }

  @override
  State<WishPublishHomePage> createState() => _WishPublishHomePageState();
}

class _WishPublishHomePageState extends BJHBasePageState<WishPublishHomePage> {
  AppRefreshController _refreshController;

  int pageNum = 1;
  bool _enablePullUp = true;
  List<WishTemplateModel> _templateModels;

  StreamSubscription _loginSuccessEmitter;
  StreamSubscription tsdemoSpaceEvent;

  @override
  void initState() {
    super.initState();

    _addListens();

    _loadCacheData();

    _refreshController = AppRefreshController(initialRefresh: false);
  }

  _loadCacheData() async {
    _templateModels = [];
    /*
    for (var i = 0; i < 5; i++) {
      _templateModels.add(WishTemplateModel());
    }
    */

    /// 一开始的时候就去取缓存数据，避免等到 StatefulWidget addPostFrameCallback 渲染结束的时候才去获取
    /// 或者等到下拉结束的时候才去请求
    _templateModels = await LocalStorage.getCustomBeans(
      "tsdemoTemplateModels",
      fromJson: (bMap) {
        return WishTemplateModel.fromJson(bMap);
      },
    );
    _templateModels ??= [];
  }

  _addListens() {
    _loginSuccessEmitter = eventBus.on<LoginSuccessEvent>().listen((event) {
      _onRefresh();
    });

    /// 点击底部tab要回到滚动视图头部
    tsdemoSpaceEvent = eventBus.on<TabCreateTop>().listen((event) {
      PrimaryScrollController.of(context).animateTo(
        0,
        duration: const Duration(milliseconds: 300),
        curve: Curves.linear,
      );
    });

    /// 网络变化(无网络 -> 有网络)
    networkEventBus.on<NetworkTypeChangeEvent>().listen((event) {
      NetworkType connectionStatus = event.connectionStatus;
      if (currentWidgetType == WidgetType.ErrorNetwork &&
          connectionStatus != NetworkType.none) {
        _onRefresh();
      }
    });
  }

  @override
  void viewDidAppear(AppearBecause appearBecause) {
    super.viewDidAppear(appearBecause);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      // _requestTemplatesData();
    });
  }

  @override
  void dispose() {
    _loginSuccessEmitter.cancel();
    super.dispose();
  }

  /*
  @override
  Widget backgroundWidget(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        // gradient: LinearGradient(
        //   colors: [Colors.amberAccent, Colors.lightBlue, Colors.red],
        //   begin: Alignment.topCenter,
        //   end: Alignment.bottomCenter,
        // ),
      ),
    );
  }
  */

  @override
  Widget appBarWidget(BuildContext context) {
    if (WishPublishHomePage.isPresent == true) {
      return CommonAppBar(
        title: const ToolBarTitleWidget(
          text: "选择模版",
        ),
        leading: ToolBarImageActionWidget(
          // width: width,
          // textColor: textColor,
          color: Colors.transparent,
          image: Image(
            image: const AssetImage(
              'assets/log_close.png',
              package: 'flutter_log',
            ),
            fit: BoxFit.cover,
            width: 22.w_bj,
            height: 22.h_bj,
          ),
          onPressed: () {
            FocusScope.of(context).requestFocus(FocusNode()); // 默认返回时候,关闭键盘
            Navigator.pop(context);
          },
        ),
      );
    }
    return QuickAppBar(
      context,
      title: "选择模版",
      backgroundColor: Colors.transparent,
      automaticallyImplyLeading: false,
      /*
      customOnPressedBack: () {
        FocusScope.of(context).requestFocus(FocusNode());
        EventCenter.defaultCenter().fire("goHome");
      },
      */
      // actions: [_renderRefreshBtn()],
    );
  }

  @override
  Widget buildErrorWidget(BuildContext context) {
    return StateErrorWidget(errorRetry: _onRefresh);
  }

  @override
  Widget buildNodataWidget(BuildContext context) {
    return super.buildNodataWidget(context);
  }

  @override
  Widget buildSuccessWidget(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        AppRefreshContainer(
          controller: _refreshController,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          enablePullDown: true,
          enablePullUp: _enablePullUp,
          child: Container(
            padding: EdgeInsets.only(
              // left: 15.w_bj,
              // right: 15.w_bj,
              top: Adapt.px(20),
            ),
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.only(left: 15.w_bj, right: 15.w_bj),
                  child: _topQuickButton(context),
                ),
                SizedBox(height: Adapt.px(32)),
                Visibility(
                  visible: _templateModels.isNotEmpty,
                  child: listHeader(context),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 15.w_bj, right: 15.w_bj),
                  child: ListView.builder(
                    itemCount: _templateModels.length,
                    padding: EdgeInsets.fromLTRB(0, 0, 0, Adapt.px(120)),
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      WishTemplateModel model = _templateModels[index];
                      return _renderItem(model, index, context);
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget listHeader(BuildContext context) {
    return Container(
      height: Adapt.px(135),
      padding: EdgeInsets.only(
        left: Adapt.px(72),
        right: Adapt.px(68),
        bottom: Adapt.px(20),
      ),
      // color:[Color.fromRGBO(63, 68, 72, 1), Color.fromRGBO(36, 41, 46, 1)],
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Color.fromRGBO(255, 255, 255, 1),
            Color.fromRGBO(247, 247, 247, 1)
          ],
        ),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(Adapt.px(32)),
          topRight: Radius.circular(Adapt.px(32)),
        ),
      ),
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Center(
            child: Text(
              "点击以下模版，快速创建清单",
              style: TextStyle(
                fontSize: Adapt.px(30),
                color: const Color(0xFF333333),
                fontWeight: FontWeight.w400,
              ),
            ),
          ),
          _renderRefreshBtn(),
        ],
      ),
    );
  }

  void _onRefresh({bool isTapAction}) {
    pageNum = 1;
    _requestTemplatesData(isTapAction: isTapAction);
  }

  void _onLoading() {
    pageNum += 1;
    _requestTemplatesData();
  }

  // isTapAction 是否是点击事件，而不是下拉加载事件
  void _requestTemplatesData({bool isTapAction}) {
    if (pageNum == 1) {
      _templateModels.clear();
    }

    if (isTapAction == true) {
      LoadingUtil.showInContext(context, minLoadingMilliseconds: 500);
    }

    int perPageSize = 20;
    AppNetworkKit.postWithCallback(
      UrlPath.tsdemoGetWishTemplate,
      params: {
        "pageNum": pageNum,
        "pageSize": perPageSize,
      },
      // cacheLevel: NetworkCacheLevel.one, // (模板页不使用缓存，避免启动时候，因为后台返回数据与缓存不一致，导致刷新两次)，已使用 LocalStorage
      completeCallBack: (ResponseModel responseModel) {
        _refreshController.refreshCompleted();
        _refreshController.loadComplete();

        LoadingUtil.dismissInContext(context);

        if (responseModel.isSuccess != true) {
          updateWidgetType(WidgetType.ErrorNetwork);
          return;
        }

        List list = responseModel.result["resultList"];
        // list = []; // 测试
        // if (list.isEmpty) {
        //   updateWidgetType(WidgetType.SuccessNoData);
        //   return;
        // }

        for (var model in list) {
          _templateModels.add(WishTemplateModel.fromJson(model));
        }

        LocalStorage.saveCustomBeans(
          "tsdemoTemplateModels",
          _templateModels,
          itemToJson: (bItem) {
            return bItem.toJson();
          },
        );

        if (list.length < perPageSize) {
          _enablePullUp = false;
        } else {
          _enablePullUp = true;
        }
        updateWidgetType(WidgetType.SuccessWithData);
      },
    );
  }

  bool checkModel(WishTemplateModel model) {
    if (model.tsdemoTagVOS == null || model.tsdemoTagVOS.isEmpty) {
      ToastUtil.showMessage('缺少绑定标签，无法继续操作');
      return false;
    }
    return true;
  }

  _onclickItem(WishTemplateModel model, int index) {
    if (model.id == null) {
      if (!checkModel(model)) return;
      return;
    }

    ///标签id为0时，清单为TOP内容
    if (model.tsdemoTagVOS.isNotEmpty &&
        model.tsdemoTagVOS != null &&
        model.tsdemoTagVOS.first.id == '0') {
      AppNetworkKit.post(
        UrlPath.tsdemoGetTopDetail,
      ).then((ResponseModel data) {
        if (data.result == null) {
          _onWishPublishPage(model);
        } else {
          AlertUtil.showTwoActionAlert(
            context: context,
            title: "已有TOP愿望清单",
            message: "你可以用这个模版替换已有清单",
            cancelTitle: "查看清单",
            okTitle: "编辑并替换",
            okHandle: () {
              LoadingUtil.show();
              Api.tsdemoGetDetail({
                "tsdemoId": data.result["id"],
              }).then((ResultData resultData) {
                LoadingUtil.dismiss();
                if (data.isSuccess) {
                  WishDetailModel detailModel =
                      WishDetailModel.fromJson(resultData.data);
                  WishPublishUtil.goUpdteWishDetailPage(context, detailModel);
                } else {
                  ToastUtil.showMessage(resultData.msg);
                }
              });
              // _onWishPublishPage(data.result);
            },
            cancelHandle: () {
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                return WishDetailPage(tsdemoID: data.result["id"]);
              }));
            },
          );
        }
      });
    } else {
      _onWishPublishPage(model);
    }
  }

  _onWishPublishPage(model) {
    /*
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) {
        return WishPublishHomePage();
      },
    ));
    return;
    */
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return WishPublishPage.fromTemplatePage(
        isUpdateBusiness: false,
        templateModel: model,
      );
    })).then((value) {
      debugPrint(" goPublishPage then >>>>>");
    });
  }

  _renderRefreshBtn() {
    return GestureDetector(
      onTap: () => _onRefresh(isTapAction: true),
      child: Row(
        children: [
          Container(
            width: Adapt.px(144),
            height: Adapt.px(48),
            decoration: BoxDecoration(
              color: Colors.transparent,
              borderRadius:
                  BorderRadius.all(Radius.circular(Adapt.px(142) * 0.5)),
              border: Border.all(color: const Color(0xff4d4d4d), width: 1),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // Image.asset(
                //   'images/tsdemo/icon_refresh.png',
                //   width: Adapt.px(22),
                //   height: Adapt.px(18),
                //   fit: BoxFit.fitWidth,
                // ),
                // SizedBox(width: Adapt.px(8)),
                Text(
                  '换一批',
                  style: TextStyle(
                    color: const Color(0xff4d4d4d),
                    fontSize: 13.h_bj,
                    fontWeight: FontWeight.normal,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Container _renderItem(
    WishTemplateModel model,
    int index,
    BuildContext context,
  ) {
    return Container(
      // height: 200.h_bj,
      margin: EdgeInsets.only(bottom: 15.h_bj),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.w_bj),
        // boxShadow: [
        //   BoxShadow(
        //     color: const Color(0xFF9AADC8).withOpacity(0.8), //底色,阴影颜色
        //     offset: const Offset(0.0, 3.0), //阴影xy轴偏移量
        //     blurRadius: 10, //阴影模糊程度
        //     spreadRadius: 0, //阴影扩散程度
        //   )
        // ],
      ),
      child: BJHInkWell(
        onTap: () => _onclickItem(model, index),
        child: Container(
          margin: EdgeInsets.only(left: 10.w_bj, right: 10.w_bj),
          child: Column(
            children: [
              Container(height: (245 - 227).h_bj),
              _titleAndValue(model.tsdemoTitle, model.sendWord),
              Container(height: 12.h_bj),
              model.id == null
                  ? Skeleton(
                      height: 65.h_bj,
                    )
                  : WishTemplateGoodsView(
                      goodsInfoLists: model.goodsInfoList,
                      onclickBlock: (title) {
                        _onclickItem(model, index);
                      },
                    ),
              Container(height: 25.h_bj),
            ],
          ),
        ),
      ),
    );
  }

  Widget _titleAndValue(String title, String value) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        LazyText(
          title,
          lazyHeight: 30.h_bj,
          lazyWidth: 200.w_bj,
          maxLines: 1,
          style: MediumTextStyle(
            color: const Color(0xFF000000),
            fontSize: 16.w_bj,
            height: (22 / 16).h_bj,
          ),
        ),
        Container(height: 4.h_bj),
        Row(
          children: [
            Expanded(
              child: LazyText(
                value,
                // height: 40.h_bj,
                lazyHeight: 20.h_bj,
                lazyWidth: 200.w_bj,
                maxLines: 2,
                textAlign: TextAlign.left,
                style: RegularTextStyle(
                  height: (20 / 14).h_bj,
                  fontSize: 14.w_bj,
                  color: const Color(0xFF666666),
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _topQuickButton(BuildContext context) {
    return Row(children: [
      GestureDetector(
        onTap: () => WishPublishUtil.goCreatePage(context),
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(Adapt.px(32))),
            color: Colors.white,
          ),
          width: Adapt.px(426),
          height: Adapt.px(106),
          padding: EdgeInsets.only(left: Adapt.px(100)),
          child: Row(
            children: [
              const Text(
                '新建自定义清单',
                style: TextStyle(fontWeight: FontWeight.w500),
              ),
              SizedBox(width: Adapt.px(40)),
              Image.asset(
                'images/tsdemo/add_icon.png',
                width: Adapt.px(28),
                height: Adapt.px(28),
              )
            ],
          ),
        ),
      ),
      SizedBox(width: Adapt.px(20)),
      GestureDetector(
        onTap: () {
          if (WishPublishHomePage.isPresent == true) {
            Navigator.pop(context); // present的时候
          }

          /* // 跳转到愿望空间
          WishNewMainPage.fromHomeIndex = 2;
          EventCenter.defaultCenter().fire("goWish");

          Future.delayed(const Duration(milliseconds: 10), () {
            eventBus.fire(WishSpaceTabIndex(tabIndex: 1));
          });
          */
          // 跳转到个人空间
          RouteManager.pushPage(
            context,
            RouteNames.spaceUserPage,
            arguments: {"id": UserInfoManager().userModel.id},
          );
        },
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(Adapt.px(32))),
            color: Colors.white,
          ),
          width: Adapt.px(242),
          height: Adapt.px(106),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text(
                '我的清单',
                style: TextStyle(fontWeight: FontWeight.w500),
              ),
              SizedBox(width: Adapt.px(36)),
              Image.asset(
                "images/tsdemo/more_icon 2.png",
                width: Adapt.px(18),
                height: Adapt.px(36),
                fit: BoxFit.scaleDown,
              ),
              // const Icon(Icons.arrow_forward_ios)
            ],
          ),
        ),
      )
    ]);

    // return GestureDetector(
    //   onTap: () => WishPublishUtil.goCreatePage(context),
    //   child: Container(
    //     color: Colors.transparent, // 不设置颜色，无内容区域无法响应点击
    //     height: (181 - 91).h_bj, // 24+31+35
    //     child: Row(
    //       mainAxisAlignment: MainAxisAlignment.center,
    //       children: [
    //         Container(
    //           margin: EdgeInsets.only(top: 24.h_bj, bottom: 31.h_bj),
    //           child: _rowPaddingButton(height: 35.h_bj),
    //         ),
    //       ],
    //     ),
    //   ),
    // );
  }

  Widget _rowPaddingButton({double height}) {
    return ThemeBGButton(
      width: 222.w_bj,
      height: height,
      cornerRadius: (height / 2.0).h_bj,
      bgColorType: ThemeBGType.theme,
      // imageWidget: Image(
      //   image: const AssetImage('images/icon_edit.png'),
      //   width: 27.w_bj,
      //   height: 27.h_bj,
      // ),
      // imageTitleGap: 10.w_bj,
      title: '不使用模版，创建自定义清单',
      titleStyle: ButtonMediumTextStyle(fontSize: 14.h_bj),
      onPressed: () => WishPublishUtil.goCreatePage(context),
    );
  }
}
